package com.suep.system.controller;

import com.suep.system.config.BaseR;
import com.suep.system.domain.Role;
import com.suep.system.domain.User;
import com.suep.system.service.IRoleService;
import com.suep.system.service.IUserService;
import com.suep.system.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import java.util.*;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    @GetMapping("/getUserInfo")
    public BaseR<User> loginAfter(HttpServletRequest request){
        //过滤器已经将token解密，并将用户名信息放在Attribute里面
        String username=(String)request.getAttribute("username");
        User user=userService.selectUserByUsername(username);
        user.setPassword("隐私信息不可查看");
        return new BaseR<>().ok("用户信息获取成功",user);
    }

    @PostMapping
    public BaseR login(@RequestBody Map<String,Object> loginForm){
        String username=(String) loginForm.get("username");
        String password=(String)loginForm.get("password");
        User selectedUser = userService.selectUserByUsername(username);
        if(selectedUser==null){
            return new BaseR<>().error("不存在该用户，请用户检查账号填写是否正确");
        }
        if (selectedUser.getPassword().equals(password)){
            //获取用户角色
            Role selectedRole=roleService.selectRoleByUserId(selectedUser.getId());
            if (selectedRole==null){
                return new BaseR<>().error("用户角色为空");
            }
            //生成令牌
            String token= JWTUtil.generateToken(selectedUser.getId(),selectedUser.getUsername(),selectedRole.getName());
            return new BaseR<>().ok("登录成功",token);
        }else{
            return new BaseR<>().error("密码不正确");
        }
    }
}
